package io.renren.modules.tag.utils;

import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import io.renren.modules.tag.entity.TagRulesEntity;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class SqlUtils {


    public static String buildSql(TagRulesEntity rule) {
        String propertyName = rule.getPropertyName();
        String value = rule.getValue();
        String relation = rule.getRelation();
        Integer tagCreateMode = rule.getTagCreateMode();//标签创建模式：1-主体属性2-行为
        String valueType = rule.getValueType();
        String table = getTable(tagCreateMode);
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT * FROM ").append(table).append(" WHERE ").append(getPropertyStament(propertyName)).append(" ")
                .append(" and ").append(getValueStament(value,relation,valueType)).append(";");
        return sb.toString();
    }

    private static String getTable(Integer tagCreateMode) {
        if (tagCreateMode.equals(String.valueOf(1))) {
            return "tag_admin.tb_subject_properties";
        } else return "tag_admin.tb_event_properties";

    }

    private static String getRelation(String relation) {
        String result = "=";
        if (relation.equals("等于")) {
            result="=";
        } else if (relation.equals("小于")) {
            result ="<";
        }
        return result;
    }

    private static String getPropertyStament(String propertyName) {
        return "property_name="+"'"+propertyName+"'";
    }


    private static String getValueStament(String value, String op, String valueType) {
        String s = "property_value" + getRelation(op) + "'" + getValue(value,valueType) + "'";
        return s;
    }

    private static Object getValue(String value, String valueType) {
        if (valueType.equals("整数")) {
            return Integer.valueOf(value);
        }
        return value;
    }


    public static List<Map<String, Object>> getUsers(TagRulesEntity rule) {
        String sql = buildSql(rule);
        log.debug(sql);
        List<Map<String, Object>> mapList = SqlRunner.db().selectList(sql);
        return mapList;
    }
    public static List<Object> getUsers(List<TagRulesEntity> rules) {
        List<Object> result = new ArrayList<>();
        for (int i = 0; i < rules.size(); i++) {
            TagRulesEntity rule = rules.get(i);
            String op = rule.getOp();
            List<Map<String, Object>> users = getUsers(rule);
            if(i==0 ) {
                result.addAll(users);
            } else if (op == "And") {
                result.retainAll(users);
            } else {
                result.addAll(users);
            }
        }
        return result;
    }

    public static String generateInsertSql(String tableName, List<String> values) {
        String sql = "INSERT INTO " + tableName + " VALUES";
        for (String value : values) {
            sql += "\n" + value + ",";
        }
        sql = sql.substring(0, sql.length() - 1) + ";";
        return sql;
    }
    public static String generateQuery(String[] tags) {
        String query = "select bitmap_to_string(orthogonal_bitmap_intersect(tagbitmap, tagvalue, %s)),subject from label_tag_bitmap where tagvalue in (%s) group by subject;";
        String[] tagValues = new String[tags.length];
        String[] processedTags = new String[tags.length];
        for (int i = 0; i < tags.length; i++) {
            tagValues[i] = "'" + tags[i] + "'";
            processedTags[i] = "'" + tags[i] + "'";
        }
        String tagsStr = String.join(", ", tagValues);
        String processedTagsStr = String.join(", ", processedTags);
        return String.format(query, processedTagsStr, tagsStr);
    }


    public static void main(String[] args) {
        String[] tags = {"赌博", "稳定", "治安"};
        String formattedQuery = generateQuery(tags);
        System.out.println(formattedQuery);
        String[] tags1 = {"涉毒", "涉赌", "治安"};
        formattedQuery = generateQuery(tags1);
        System.out.println(formattedQuery);
        String s = getSubjectTagSql("people",1003l);
        System.out.println(s);
        Map<String, String> map = new HashMap<>();
        Map<String, String> tagSubjectMap = new HashMap<>();
        tagSubjectMap.put("青年", "ztk_ryztxxb");
        tagSubjectMap.put("境外旅游", "ztk_ryztxxb");
        tagSubjectMap.put("频繁出行", "ztk_ryztxxb");
        tagSubjectMap.put("去往敏感地", "ztk_ryztxxb");
        tagSubjectMap.put("体育爱好者", "ztk_tyahz");
        tagSubjectMap.put("健康生活", "ztk_jkshz");
        tagSubjectMap.put("音乐爱好者", "ztk_yyahz");
        ArrayList<String> objects = new ArrayList<>(tagSubjectMap.keySet());
        s = generateSql(tagSubjectMap,objects);
        System.out.println(s);
    }

        public static String getSubjectTagSql(String subject, Long id) {
            return "select tagname, tagvalue, inserttime from label_tag_bitmap where BITMAP_CONTAINS(tagbitmap, " + id + ") and subject = '" + subject + "';";
        }

    public static String generateSql(Map<String, String> tagSubjectMap, List<String> tags) {
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("SELECT bitmapToArray(bitmapOr(");

        for (int i = 0; i < tags.size(); i++) {
            String tag = tags.get(i);
            String subject = tagSubjectMap.get(tag);

            if (subject == null) {
                throw new IllegalArgumentException("No subject found for tag: " + tag);
            }

            sqlBuilder.append("bitmapAnd((SELECT tagbitmap FROM (SELECT * FROM labelinfo.label_tag_bitmap_all WHERE subject = '")
                    .append(subject)
                    .append("') WHERE tagvalue = '")
                    .append(tag)
                    .append("'))");

            if (i < tags.size() - 1) {
                sqlBuilder.append(", ");
            }
        }

        sqlBuilder.append(")) AS customer");

        return sqlBuilder.toString();
    }


}
